package top.drinyeit.nongmao.app;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.multidex.MultiDex;
import android.util.Log;

import org.xutils.x;

import java.util.List;

import top.drinyeit.nongmao.entity.LoginResult;
import top.drinyeit.nongmao.util.AppUserDao;

import static android.content.ContentValues.TAG;


/**
 * Created by Administrator on 2017/11/9.
 */

public class MyApplication extends Application {
    private LoginResult.AppUser appUser;
    private AppUserDao appUserDao;
    private static Context mContext;
    private int appVersion = -1;
    public static Application instance;

    @Override
    public void onCreate() {
        super.onCreate();
        appVersion = getAppVersionCode();
        mContext = getApplicationContext();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
//            StrictMode.setVmPolicy(builder.build());
//        }
        initXutils();
        initDb();

    }

    public static Application getApp(){
        return instance;
    }

    public static Context getInstance(){
        return mContext;
    }

    public int getAppVersion() {
        return appVersion;
    }

    private void initDb() {
        appUserDao = new AppUserDao(appVersion != -1 ? appVersion : 1);
    }

    private int getAppVersionCode() {
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES);
            return packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }

    private void initXutils() {
        x.Ext.init(this);
    }

    public LoginResult.AppUser getAppUser() {
        if (appUser == null) {
            List<LoginResult.AppUser> users = appUserDao.findAll();
            if (users != null && users.size() > 0) {
                appUser = users.get(0);
                //登录
            }
        }
        if(appUser != null)
            Log.d(TAG,"appUser"+appUser.getId());
        return appUser;

    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}